package com.zqs.grainmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zqs.common.exception.NoStockException;
import com.zqs.common.to.mq.OrderTo;
import com.zqs.common.utils.R;
import com.zqs.common.vo.MemberResponseVo;
import com.zqs.grainmall.order.constant.OrderConstant;
import com.zqs.grainmall.order.dao.OrderItemDao;
import com.zqs.grainmall.order.entity.OrderItemEntity;
import com.zqs.grainmall.order.enume.OrderStatusEnum;
import com.zqs.grainmall.order.feign.CartFeignService;
import com.zqs.grainmall.order.feign.MemberFeignService;
import com.zqs.grainmall.order.feign.ProductFeignService;
import com.zqs.grainmall.order.feign.WmsFeignService;
import com.zqs.grainmall.order.interceptor.LoginUserInterceptor;
import com.zqs.grainmall.order.service.OrderItemService;
import com.zqs.grainmall.order.to.OrderCreateTo;
import com.zqs.grainmall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqs.common.utils.PageUtils;
import com.zqs.common.utils.Query;

import com.zqs.grainmall.order.dao.OrderDao;
import com.zqs.grainmall.order.entity.OrderEntity;
import com.zqs.grainmall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo>  confirmVoThreadLocal=new ThreadLocal<>();


    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有的收获地址列表
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            confirmVo.setMemberAddressVos(address);


        }, threadPoolExecutor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.currentUserCartItems();
            confirmVo.setItems(items);
            //feign在远程调用之前要构造请求，调用很多的拦截器
            //RequestInterceptor interceptor: requestInterceptors
        }, threadPoolExecutor).thenRunAsync(()->{
           List<OrderItemVo> items= confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            //TODO 远程查询库存状态 这里会报空指针，因为我配置了拦截器-->GrainmallFeignConfig 里面获取了cookie信息，而在这里我不需要cookie信息
            R hasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data!=null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }

        },threadPoolExecutor);



        //3.查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4.其他数据自动计算

        //5. TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResponseVo.getId(),token,30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture,cartFuture).get();



        return confirmVo;
    }

   // @GlobalTransactional //TODO 这个业务场景就不适合AT模式了
    @Transactional()  //本地事务，在分布式系统，只能控制自己的回滚，控制不了其他服务的回滚   分布式事务: 最大原因，网络问题+分布式机器
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        //获取当前用户登录的信息
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        submitOrderResponseVo.setCode(0);

        //1.验证令牌 TODO 【令牌的对比和删除必须保证原子性】 lua脚本
        //0令牌失败--1删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);

        if (result==0L)
        {
            //令牌验证失败  code=1代表失败了
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;

        }else
        {
            //令牌验证成功
            //1.创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
             payPrice=payAmount; //TODO 没有值，暂时模拟一下
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比成功
                //...
                //TODO 3. 保存订单
                saveOrder(order);
                //4.库存锁定 ..只要有异常则回滚订单数据。
                // 订单号，所有订单的订单项(skuId,skuName,num)
                WareSkuLockVO lockVO = new WareSkuLockVO();
                lockVO.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());

                lockVO.setLocks(locks);
                //TODO 4.远程锁库存
                //库存成功了，但是网络原因超时了，订单回滚，库存不滚

                //为了保证高并发。库存服务自己回滚。可以发消息给库存
                //库存服务本身也可以使用自动解锁模式 消息队列
                R r = wmsFeignService.orderLockStock(lockVO);
                if (r.getCode()==0)
                {
                    //锁成功了
                    submitOrderResponseVo.setOrder(order.getOrder());

                    //TODO 5.远程扣减积分
                   // int i=10/0;  //订单回滚，库存不滚
                    //TODO 订单创建成功发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return submitOrderResponseVo;

                }
                else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }


            }else
            {
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }


        }
        //      String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
//        if (orderToken!=null&&orderToken.equals(redisToken))
//        {
//            //令牌验证通过
//
//
//        }else {
//            //不通过
//            return null;
//        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());

        if(orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode())
        {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo=new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //TODO 关单完了再发给MQ一个消息解锁库存
            try {
                //TODO 保存消息一定会发送出去,每一个消息都做好日志记录(给数据库保存每一个消息都详细信息)
                //TODO 定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e)
            {
                //TODO 将没发送成功的消息进行重试发送


            }

        }

    }


    /**
     * 保存订单数据
     * */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        //设置修改时间
        orderEntity.setModifyTime(new Date());

        //保存订单
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        //保存订单项数据
        orderItemService.saveBatch(orderItems);

    }


    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //TODO 1.生成一个订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //TODO 2.获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //TODO 3.验价  计算价格、积分等相关
        computePrice(orderEntity,itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);



        return createTo;

    }


    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integrationAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            BigDecimal realAmount = entity.getRealAmount();
            coupon=coupon.add(entity.getCouponAmount());
            integrationAmount=integrationAmount.add(entity.getIntegrationAmount());
            promotionAmount=promotionAmount.add(entity.getPromotionAmount());
            total= total.add(realAmount);
            gift =gift.add(new BigDecimal(entity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth()));

        }
        //1.订单价格相关的
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        orderEntity.setCouponAmount(coupon);

        //设置积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);  //未删除



    }


    /**
     * 创建订单
     * */
    private OrderEntity buildOrder(String orderSn) {
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        //创建订单号
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());
        entity.setMemberUsername(respVo.getUsername());

        OrderSubmitVo submitVo = confirmVoThreadLocal.get(); //1.使用ThreadLocal来获取OrderSubmitVoz中的addrId
        //获取收货地址信息/运费   2.根据addrId远程查询收货地址信息/运费
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData("data",new TypeReference<FareVo>() {});

        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //设置默认收货时间
        entity.setAutoConfirmDay(7);
        //
        entity.setConfirmStatus(0);

        return entity;
    }



    /**
     * 构建所有订单项数据
     *
     * */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //远程调用 获取购物车数据  最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.currentUserCartItems(); //这里要经过拦截器，由于没有做异步，所以不需要去共享上下文
        if(currentUserCartItems!=null&&currentUserCartItems.size()>0)
        {
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity =buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());

            return collect;
        }

        return null;

    }


    /**
     * 构建某一个订单项
     *
     * */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息:订单号
        //2.商品的spu信息
        Long skuId = cartItem.getSkuId();
        //远程查询spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = spuInfo.getData(new TypeReference<SpuInfoVo>() {});
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setCategoryId(data.getCatalogId());

        //3.商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //用spring家的工具类把集合转换为一个String,并且以;为分隔符
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());

        //4.优惠信息(不做)
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6.订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //multiply *  当前订单项的实际金额  总额-各种优惠
        BigDecimal orgin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orgin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount()
                        .subtract(itemEntity.getIntegrationAmount()));
        itemEntity.setRealAmount(subtract);


        return itemEntity;
    }

}